import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const REGION_BASE = "/system/region/regions";
const REGION_USER_BASE = "/system/region/users";

export const REGION_STATUS_OPTIONS = [
  { label: "禁用", value: 0 },
  { label: "启用", value: 1 }
];

export interface RegionFilterParams {
  page?: number;
  page_size?: number;
  keyword?: string;
  status?: number | string;
  parent_id?: number | string;
  level?: number | string;
}

export interface RegionItem {
  id: number;
  name: string;
  code: string;
  parent_id: number;
  level: number;
  path: string;
  sort: number;
  status: number;
  label: string;
  full_path: string;
  seller_count: number;
  buyer_count: number;
  create_time?: string;
  update_time?: string;
  children?: RegionItem[];
}

export interface RegionListResult {
  list: RegionItem[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
}

const mapRegion = (item: Record<string, any>): RegionItem => {
  const rawName = item.name ?? item.label ?? item.title ?? "";
  const fallbackPath =
    item.full_name ??
    item.full_path ??
    item.path_name ??
    item.path_label ??
    rawName;

  return {
    id: toNumber(item.id, 0),
    name: rawName,
    code: item.code ?? "",
    parent_id: toNumber(item.parent_id, 0),
    level: toNumber(item.level, 0),
    path: item.path ?? "",
    sort: toNumber(item.sort, 0),
    status: toNumber(item.status, 0),
    label: fallbackPath || rawName,
    full_path: fallbackPath || rawName,
    seller_count: toNumber(item.seller_count, 0),
    buyer_count: toNumber(item.buyer_count, 0),
    create_time: item.create_time ?? "",
    update_time: item.update_time ?? "",
    children: ensureArray<Record<string, any>>(item.children ?? []).map(
      mapRegion
    )
  };
};

export const fetchRegionList = async (
  params: RegionFilterParams = {}
): Promise<RegionListResult> => {
  const page = toNumber(params.page, 1) || 1;
  const pageSize = toNumber(params.page_size, 10) || 10;

  const res = await http.request<ApiResponse<any>>("get", REGION_BASE, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (res?.data ?? {}) as Record<string, any>;
  const list = ensureArray<Record<string, any>>(
    payload.list ?? payload.data ?? []
  ).map(mapRegion);
  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination
  };
};

export const fetchRegionTree = async (
  params: Partial<RegionFilterParams> = {}
): Promise<RegionItem[]> => {
  const res = await http.request<ApiResponse<any>>("get", REGION_BASE, {
    params: {
      ...params,
      as_tree: true
    }
  });

  const payload = ensureArray<Record<string, any>>(res?.data ?? []);
  return payload.map(mapRegion);
};

export const fetchRegionDetail = async (
  id: number | string
): Promise<RegionItem> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${REGION_BASE}/${id}`
  );
  return mapRegion(res.data ?? {});
};

export const createRegion = async (payload: Record<string, any>) => {
  return http.request<ApiResponse<any>>("post", REGION_BASE, {
    data: payload
  });
};

export const updateRegion = async (
  id: number | string,
  payload: Record<string, any>
) => {
  return http.request<ApiResponse<any>>("put", `${REGION_BASE}/${id}`, {
    data: payload
  });
};

export const deleteRegion = async (id: number | string) => {
  return http.request<ApiResponse<boolean>>("delete", `${REGION_BASE}/${id}`);
};

export interface RegionUserFilterParams {
  page?: number;
  page_size?: number;
  region_id?: number | string;
  user_id?: number | string;
  role_type?: string;
  status?: number | string;
}

export interface RegionUserItem {
  id: number;
  region_id: number;
  user_id: number;
  role_type: string;
  is_primary: number;
  status: number;
  config: Record<string, any>;
  create_time?: string;
  update_time?: string;
  region?: {
    id: number;
    name: string;
    code: string;
  } | null;
  user?: Record<string, any> | null;
}

export const REGION_USER_ROLE_OPTIONS = [
  { label: "负责人", value: "manager" },
  { label: "运营人员", value: "operator" }
];

export const fetchRegionUserList = async (
  params: RegionUserFilterParams = {}
): Promise<{
  list: RegionUserItem[];
  pagination: { total: number; pageSize: number; currentPage: number };
}> => {
  const page = toNumber(params.page, 1) || 1;
  const pageSize = toNumber(params.page_size, 10) || 10;

  const res = await http.request<ApiResponse<any>>("get", REGION_USER_BASE, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (res?.data ?? {}) as Record<string, any>;
  const list = ensureArray<Record<string, any>>(
    payload.list ?? payload.data ?? []
  ).map(item => ({
    id: toNumber(item.id, 0),
    region_id: toNumber(item.region_id, 0),
    user_id: toNumber(item.user_id, 0),
    role_type: item.role_type ?? "manager",
    is_primary: toNumber(item.is_primary, 0),
    status: toNumber(item.status, 0),
    config:
      item.config && typeof item.config === "object" ? { ...item.config } : {},
    create_time: item.create_time ?? "",
    update_time: item.update_time ?? "",
    region: item.region
      ? {
          id: toNumber(item.region.id, 0),
          name: item.region.name ?? "",
          code: item.region.code ?? ""
        }
      : null,
    user: item.user ?? null
  }));
  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination
  };
};

export const fetchRegionUserDetail = async (
  id: number | string
): Promise<RegionUserItem> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${REGION_USER_BASE}/${id}`
  );
  const data = res.data ?? {};
  return {
    id: toNumber(data.id, 0),
    region_id: toNumber(data.region_id, 0),
    user_id: toNumber(data.user_id, 0),
    role_type: data.role_type ?? "manager",
    is_primary: toNumber(data.is_primary, 0),
    status: toNumber(data.status, 0),
    config:
      data.config && typeof data.config === "object" ? { ...data.config } : {},
    create_time: data.create_time ?? "",
    update_time: data.update_time ?? "",
    region: data.region
      ? {
          id: toNumber(data.region.id, 0),
          name: data.region.name ?? "",
          code: data.region.code ?? ""
        }
      : null,
    user: data.user ?? null
  };
};

export const createRegionUser = async (payload: Record<string, any>) => {
  return http.request<ApiResponse<any>>("post", REGION_USER_BASE, {
    data: payload
  });
};

export const updateRegionUser = async (
  id: number | string,
  payload: Record<string, any>
) => {
  return http.request<ApiResponse<any>>("put", `${REGION_USER_BASE}/${id}`, {
    data: payload
  });
};

export const deleteRegionUser = async (id: number | string) => {
  return http.request<ApiResponse<boolean>>(
    "delete",
    `${REGION_USER_BASE}/${id}`
  );
};

export default {
  fetchList: fetchRegionList,
  fetchTree: fetchRegionTree,
  fetchDetail: fetchRegionDetail,
  create: createRegion,
  update: updateRegion,
  remove: deleteRegion,
  fetchRegionUsers: fetchRegionUserList,
  fetchRegionUserDetail,
  createRegionUser,
  updateRegionUser,
  deleteRegionUser
};
